package ldh.im.server.websocket.initialize;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateHandler;
import ldh.im.base.handler.HeartBeatServerHandler;
import ldh.im.base.handler.ToHandler;
import ldh.im.base.handler.service.HandlerService;
import ldh.im.base.handler.service.ThreadHandlerService;

import java.util.concurrent.TimeUnit;

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    private static final int MAX_AGGREGATOR = 65536;

    private HandlerService handlerService = new ThreadHandlerService(Runtime.getRuntime().availableProcessors());

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new IdleStateHandler(2,5,7, TimeUnit.MINUTES))
            .addLast(new HttpServerCodec())
            .addLast(new HttpObjectAggregator(MAX_AGGREGATOR))
            .addLast(new WebSocketServerProtocolHandler("/imwebsocket"))
            .addLast(new HeartBeatServerHandler())
            .addLast(new ToHandler(handlerService))
            ;
    }
}
